//
//  AppIcon.swift
//  Lease_IOS
//
//  Created by Mr.wang on 2019/4/29.
//  Copyright © 2019 Mr.wang. All rights reserved.
//

import UIKit

struct AppIcon {

    static let shared = AppIcon()
    private let fontLabel = UILabel()
    
    fileprivate init() {
        guard let fontUrl = Bundle.main.path(forResource: "iconfont", ofType: "ttf"),
            let fontData = try? Data.init(contentsOf: URL.init(fileURLWithPath: fontUrl)) as CFData,
            let provider = CGDataProvider(data: fontData),
            let font = CGFont(provider) else { return }
        CTFontManagerRegisterGraphicsFont(font, nil)
        
        fontLabel.backgroundColor = UIColor.clear
        fontLabel.textAlignment = .center
        fontLabel.accessibilityElementsHidden = true
    }
    
    static func image(_ text: String,
                      size: CGFloat = 20,
                      color: UIColor = .black) -> UIImage? {
        
        AppIcon.shared.fontLabel.text = text
        AppIcon.shared.fontLabel.font = UIKit.UIFont(name: "iconfont", size: size)
        AppIcon.shared.fontLabel.sizeToFit()
        AppIcon.shared.fontLabel.textColor = color
        
        UIGraphicsBeginImageContextWithOptions(AppIcon.shared.fontLabel.bounds.size, false, UIScreen.main.scale)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        AppIcon.shared.fontLabel.layer.render(in: context)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    
}
